const express = require('express');
const router = express.Router();
const crypto = require('crypto');
const jwt = require('jsonwebtoken'); //引用jwt
const authenticator = require('../middleware/authenticator');
const axios = require('axios');

//生成一个随机盐
const salt = crypto.randomBytes(16).toString('hex');


const secretKey = 'pp7_secret_key'; //密钥

const generateToken = (userId, username) => {
    const payload = {
        userId,
        username
    };
    const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });
    return token;
}


function userRouteModule(db) {


    // 用户登录
    router.post("/login", async (req, res) => {
        console.log(req.body)
        const { code } = req.body;
        const appId = 'wxb1290600736cde59'; // 替换为你的小程序 AppID
        const appSecret = 'dceee70940b6b5c99645fd5b8848f5ef'; // 替换为你的小程序 AppSecret
        try {
            const wechatResponse = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
                params: {
                    appid: appId,
                    secret: appSecret,
                    js_code: code,
                    grant_type: 'authorization_code',
                },
            });

            const { openid, session_key } = wechatResponse.data;
            // 在这里可以根据 openid 查询或创建用户信息
            // 插入新用户记录
            const [userId] = await db.execute(
                'INSERT INTO user (Username, Password, Role, CreateTime, salt) VALUES (?, ?, ?, NOW(), ?)',
                ['默认用户', 'default_password', '普通用户', 'random_salt'] // 这里需要根据实际情况设置默认值
            );
            userId[0] = userId[0].insertId; // 获取新插入的用户ID

            // 插入第三方登录记录
            await db.execute(
                'INSERT INTO third_party_login (UserId, Provider, ProviderId, AccessToken, RefreshToken, CreatedAt, UpdatedAt) VALUES (?, ?, ?, ?, ?, NOW(), NOW())',
                [userId, 'wechat', openid, session_key, session_key]
            );

            res.json({ code: 200, message: 'ok', data: { openid, session_key } });
        } catch (error) {
            console.error('登录失败:', error);
            if (error.response) {
                res.status(500).json({ success: false, message: error.response.data.errmsg });
            } else {
                res.status(500).json({ success: false, message: '登录失败，服务器错误' });
            }
        }
    })

    return router;
}





module.exports = userRouteModule;
